package cnrpc

import (
	"context"
	"fmt"
	"log"
	"net"

	"google.golang.org/grpc"
)

type (
	Server struct {
		EtcdURL     string //etcd的访问地址
		ServiceName string //服务名称
		Port        int    //服务端口
	}
)

func NewServer(etcdURL, serviceName string, port int) *Server {
	server := new(Server)
	server.EtcdURL = etcdURL
	server.ServiceName = serviceName
	server.Port = port
	return server
}

func (server *Server) Start(s *grpc.Server) {
	port := server.Port
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	log.Printf("server listening at %v", lis.Addr())
	// 接收命令行指定的 grpc 服务端口
	addr := fmt.Sprintf("localhost:%d", port)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	// 注册 grpc 服务节点到 etcd 中
	register := NewRegister(server.EtcdURL, server.ServiceName, addr, 10)
	var registrar Registrar = register
	go registrar.Register(ctx)

	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
